package com.studyadmin.util;

//import com.bean.UserBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.studyadmin.entity.Role;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * Jwt加密和解密
 */
public class JwtToken {

        private String secret="JO6HN3NGIU25G2FIG1V7VD6CK9B6T2A6";//密钥

        private long expire=60*1000*60*4;

        /**
         * 生成jwt token
         */
        public String generateToken(String json) {
            Date nowDate = new Date();
            Date expireDate = new Date(nowDate.getTime() + expire );

            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;    //把一段文件信息进行加密，产生加密字符串，并且设置过期时间

            return Jwts.builder()
                    .setHeaderParam("typ", "JWT")
                    .setSubject(json + "")//被加密的字符串 （登录用户名称）
                    .setIssuedAt(nowDate)//当前系统 时间
                    .setExpiration(expireDate)   //过期时间
                    .signWith(signatureAlgorithm, secret.getBytes())  // new String(org.apache.commons.codec.binary.Base64.encodeBase64(secret.getBytes()) 把密钥用Base64加密
                    .compact();
            //.signWith(SignatureAlgorithm.HS512, secret)
            //.compact();
        }


        public Claims getClaimByToken(String token) { //把generateToken产生的字符串进行解密,得到Claims对象

            try {
                SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
                return Jwts.parser()
                        .setSigningKey(secret.getBytes())
                        .parseClaimsJws(token)
                        .getBody();
            } catch (Exception e) {
                System.out.println("jwt 解密失败");
                e.printStackTrace();;
                return null;
            }
        }

    /**
     * 根据前端传递过来的请求头  access_token 获得jwt加密串，
     * 再从jwt加密串中取出登录用户信息，返回UserBean对象
     *
     * @param request
     * @return
     * @throws AuthenticationException
     */
        public Role getLoginUserBean(HttpServletRequest request) throws AuthenticationException {

            String access_token =  request.getHeader("access_token");//获得get或post传递过来的access_token值（LayerUI）

            Claims claims = getClaimByToken(access_token);//jwtToken.getClaimByToken(access_token);

            if (claims == null || JwtToken.isTokenExpired(claims.getExpiration()) ) {
                throw new AuthenticationException("access_token 过期");
            }
            //url :http://localhost:8080/rolegroup/listByPage
            //rolegroup
            //admin@operator/operatorList@rolegroup/list@dept/list@PHONEuser/list@PHONEifo/list@PHONEbill/list

            //获得用户帐号是第一个@符号前的内容

            //String tokenVal  = claims.getSubject();//得到登录用户json串

            String loginUserJson =    claims.getSubject();//得到登录用户信息，被JOSN转换后的json串
            //把登录用户json串转换成UserBean
            ObjectMapper objectMapper = new ObjectMapper();

            try {
                Role ub =  objectMapper.readValue(loginUserJson, Role.class);
                return  ub;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            return null;
        }
    /*public Claims getClaimByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }

        String[] header = token.split("Bearer");
        token = header[1];
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            logger.debug("validate is token error ", e);
            return null;
        }
    }*/

        /**
         * token是否过期
         * @return  true：过期
         */
        public static boolean isTokenExpired(Date expiration) {
            return expiration.before(new Date());
        }

        // Getter && Setter
    }